﻿using System;
using System.Reflection;

namespace CodeLibrary.Reflection.Delegate
{
    public class GetterWrapper<TTarget, TValue> : IGetValue
    {
        private Func<TTarget, TValue> _getter;

        public GetterWrapper(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null)
                throw new ArgumentNullException("propertyInfo");

            if (propertyInfo.CanRead == false)
                throw new InvalidOperationException("属性不支持读操作。");

            MethodInfo m = propertyInfo.GetGetMethod(true);
            _getter = (Func<TTarget, TValue>)System.Delegate.CreateDelegate(typeof(Func<TTarget, TValue>), null, m);
        }

        public TValue GetValue(TTarget target)
        {
            return _getter(target);
        }
        object IGetValue.Get(object target)
        {
            return _getter((TTarget)target);
        }
    }

}
